import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { ObjectId } from 'mongoose';
import { Observable } from 'rxjs';
import { CacheService } from '../module/cache/cache.service';
import { UsrDocument } from '../module/usr/schemas/usr.schema';

@Injectable()
export class TokenGuard implements CanActivate {
  constructor(
    @Inject(CacheService.name) private readonly CacheService: CacheService
  ) { }

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    let request = context.switchToHttp().getRequest()
    let token = request.header['token']
    console.log(token)
    let usrId = await this.CacheService.get<ObjectId>(token)
    let doc = this.CacheService.get<UsrDocument>(usrId.toString())
    if (doc) {
      request.user = doc
    }
    return true;
  }
}
